#!/usr/bin/env python3
"""Line-drawing pass for make_motion_clip.sh (the better pass, 8 Oct 2026).

Local contrast (CLAHE) lifts faces in dark footage without blowing the noise up into blobs, a bilateral
filter cleans grain while keeping edges, and Canny draws thin lines with thresholds set from each frame's
own brightness. Small sources are worked at 2x so the lines keep their shape, then scaled to 1280.

Usage: sketch_pass.py IN OUT START DURATION DARK(0/1)
Writes a silent intermediate video; make_motion_clip.sh encodes it to the final size.
"""
import sys, cv2, numpy as np

src, out, start, dur, dark = sys.argv[1], sys.argv[2], float(sys.argv[3]), float(sys.argv[4]), sys.argv[5] == "1"
lo, hi = (0.2, 0.55) if dark else (0.4, 1.0)      # dark footage needs lower thresholds or the figures break up

cap = cv2.VideoCapture(src)
fps = cap.get(cv2.CAP_PROP_FPS) or 30
cap.set(cv2.CAP_PROP_POS_MSEC, start * 1000)
ok, f = cap.read()
if not ok: sys.exit("could not read the video")
H0, W0 = f.shape[:2]
s = 2.0 if max(W0, H0) < 900 else 1.0
if W0 >= H0: W, H = 1280, int(round(H0 * 1280 / W0 / 2) * 2)
else: W, H = int(round(W0 * 1280 / H0 / 2) * 2), 1280
vw = cv2.VideoWriter(out, cv2.VideoWriter_fourcc(*"mp4v"), fps, (W, H))
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8))
n = 0
while ok and n < int(dur * fps):
    g = clahe.apply(cv2.cvtColor(f, cv2.COLOR_BGR2GRAY))
    g = cv2.bilateralFilter(g, 7, 40, 7)
    if s != 1: g = cv2.resize(g, None, fx=s, fy=s, interpolation=cv2.INTER_CUBIC)
    m = float(np.median(g))
    e = cv2.Canny(g, int(max(0, lo * m)), int(min(255, hi * m)))
    vw.write(cv2.cvtColor(cv2.resize(255 - e, (W, H), interpolation=cv2.INTER_AREA), cv2.COLOR_GRAY2BGR))
    n += 1
    ok, f = cap.read()
vw.release()
print(n)
